package com.studyjava.guessdx;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Xml;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;


import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import android.media.MediaPlayer;


public class choose_pic_blood extends AppCompatActivity {

    private TextView textViewIdStr, errorCountTextView, correctCountTextView;
    private TextView highestCorrectCountTextView; // 新增的 TextView
    private GridLayout imageGrid;
    private int correctId;
    private String correctStr;
    private String correctFileName;
    private int userScore;  // 用户积分
    private int errorCount = 0; // 错误次数
    private int correctCount = 0; // 累计正确次数
    private int maxErrorsAllowed = 3;  // 初始允许错误次数
    private TextView scoreTextView;  // 显示积分的文本框
    private Button skipButton;  // 跳过按钮
    private int highestCorrectCount = 0; // 历史最高正确次数

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.choose_pic_blood);

        textViewIdStr = findViewById(R.id.textView);
        scoreTextView = findViewById(R.id.scoreTextView);
        skipButton = findViewById(R.id.skipButton);
        errorCountTextView = findViewById(R.id.errorCountTextView);  // 错误次数显示
        correctCountTextView = findViewById(R.id.correctCountTextView);  // 正确次数显示
        imageGrid = findViewById(R.id.gridLayout);

        // 新增 TextView 的初始化
        highestCorrectCountTextView = findViewById(R.id.highestCorrectCountTextView);

        // 加载用户的积分
        loadUserScore();

        // 检查并初始化历史记录标签
        checkAndInitializeHistoryRecords();

        // 加载历史记录
        loadHistoryRecords();

        // 设置跳过按钮点击事件
        skipButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadAndDisplayImages();  // 跳过当前问题，加载新问题
            }
        });

        // 使用 ViewTreeObserver 确保布局加载完成后再设置子项大小
        ViewTreeObserver viewTreeObserver = imageGrid.getViewTreeObserver();
        if (viewTreeObserver.isAlive()) {
            viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    imageGrid.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                    loadAndDisplayImages();
                }
            });
        }
    }

    // 检查并创建历史记录标签
    private void checkAndInitializeHistoryRecords() {
        boolean isHighestCorrectCountExist = false;
        boolean isLastCorrectCountExist = false;

        try {
            InputStream inputStream = openFileInput("userdata.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();
                if (eventType == XmlPullParser.START_TAG) {
                    if ("highestCorrectCount".equals(tagName)) {
                        isHighestCorrectCountExist = true;
                    }
                    if ("lastCorrectCount".equals(tagName)) {
                        isLastCorrectCountExist = true;
                    }
                }
                eventType = parser.next();
            }
            inputStream.close();

            // 如果标签不存在，初始化数据
            if (!isHighestCorrectCountExist || !isLastCorrectCountExist) {
                initializeHistoryRecords(isHighestCorrectCountExist, isLastCorrectCountExist);
            }
        } catch (Exception e) {
            // 如果文件不存在，则初始化新文件和标签
            initializeHistoryRecords(false, false);
        }
    }

    // 初始化历史记录数据
    private void initializeHistoryRecords(boolean hasHighestCorrectCount, boolean hasLastCorrectCount) {
        try {
            FileOutputStream fileOutputStream = openFileOutput("userdata.xml", MODE_PRIVATE);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileOutputStream, "UTF-8");

            serializer.startDocument("UTF-8", true);
            serializer.startTag(null, "UserData");

            // 保存最高正确次数记录，如果不存在则初始化为 0
            if (!hasHighestCorrectCount) {
                serializer.startTag(null, "highestCorrectCount");
                serializer.text("0");
                serializer.endTag(null, "highestCorrectCount");
            }

            // 保存上次正确次数记录，如果不存在则初始化为 0
            if (!hasLastCorrectCount) {
                serializer.startTag(null, "lastCorrectCount");
                serializer.text("0");
                serializer.endTag(null, "lastCorrectCount");
            }

            serializer.endTag(null, "UserData");
            serializer.endDocument();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void parseXMLAndSetTextView() {
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xpp = factory.newPullParser();
            InputStream inputStream = getAssets().open("MusicSort.xml");
            xpp.setInput(inputStream, null);

            List<Integer> ids = new ArrayList<>();
            List<String> strs = new ArrayList<>();
            int eventType = xpp.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tag = xpp.getName();
                if (eventType == XmlPullParser.START_TAG && "id".equals(tag)) {
                    ids.add(Integer.parseInt(xpp.nextText()));
                } else if (eventType == XmlPullParser.START_TAG && "str".equals(tag)) {
                    strs.add(xpp.nextText());
                }
                eventType = xpp.next();
            }
            inputStream.close();

            Random random = new Random();
            int randomIndex = random.nextInt(ids.size());
            correctId = ids.get(randomIndex);
            correctStr = strs.get(randomIndex);

            textViewIdStr.setText("ID: " + correctId + "\nStr: " + correctStr);

            correctFileName = String.format("UI_Jacket_%06d.png", correctId > 9999 ? correctId - 10000 : correctId);
        } catch (IOException | XmlPullParserException e) {
            e.printStackTrace();
        }
    }

    private void loadAndDisplayImages() {
        parseXMLAndSetTextView();

        imageGrid.removeAllViews();

        List<String> imageFiles = new ArrayList<>();
        try {
            String[] files = getAssets().list("music_pic");
            for (String file : files) {
                if (file.startsWith("UI_Jacket_")) {
                    imageFiles.add(file);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        imageFiles.remove(correctFileName);
        Collections.shuffle(imageFiles);
        int correctImagePosition = (int) (Math.random() * 9);
        imageFiles.add(correctImagePosition, correctFileName);

        imageGrid.setColumnCount(3);
        int gridWidth = imageGrid.getWidth();

        for (int i = 0; i < 9; i++) {
            final String imageName = imageFiles.get(i);
            ImageView imageView = new ImageView(this);
            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
            int imageSize = gridWidth / 3;
            layoutParams.width = imageSize;
            layoutParams.height = imageSize;
            layoutParams.setMargins(0, 0, 0, 0);
            imageView.setLayoutParams(layoutParams);
            imageView.setImageBitmap(loadImageFromAssets("music_pic/" + imageName));

            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (imageName.equals(correctFileName)) {
                        userScore += 1;  // 答对加1分
                        correctCount++;
                        if (correctCount % 10 == 0) {
                            maxErrorsAllowed++;  // 每答对10次增加1次允许错误次数
                            userScore += 5;  // 每答对10次加5分
                            if (maxErrorsAllowed > 10) {
                                maxErrorsAllowed = 10;  // 错误次数最多累积10次
                            }
                        }
                        saveUserScore();  // 保存积分
                        updateHistoryRecords();  // 更新历史记录
                        loadAndDisplayImages();  // 加载新问题
                        updateCorrectAndErrorCountDisplay();
                    } else {
                        errorCount++;  // 错误次数增加
                        saveUserScore();  // 保存积分
                        updateCorrectAndErrorCountDisplay();
                        if (errorCount >= maxErrorsAllowed) {
                            endGame();  // 错误次数达到上限，结束游戏
                        } else {
                            Toast.makeText(choose_pic_blood.this, "错误，请再试一次！", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
            imageGrid.addView(imageView);
        }
    }

    private void endGame() {

        // 弹出对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("游戏结束");
        builder.setMessage("累计正确次数: " + correctCount);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                updateHistoryRecords();
                finish();  // 关闭活动
            }
        });
        builder.show();
    }

    private void loadHistoryRecords() {
        try {
            InputStream inputStream = openFileInput("userdata.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();
                if (eventType == XmlPullParser.START_TAG) {
                    if ("highestCorrectCount".equals(tagName)) {
                        highestCorrectCount = Integer.parseInt(parser.nextText());
                    }
                }
                eventType = parser.next();
            }
            inputStream.close();

            // 更新历史最高次数和上次正确次数的 TextView
            highestCorrectCountTextView.setText("历史最高正确次数: " + highestCorrectCount);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void updateHistoryRecords() {
        // 如果当前正确次数大于历史最高记录，更新历史记录
        boolean isNewRecord = false;
        if (correctCount > highestCorrectCount) {
            highestCorrectCount = correctCount;
            isNewRecord = true;
        }


        // 保存数据到 XML
        try {
            FileOutputStream fileOutputStream = openFileOutput("userdata.xml", MODE_PRIVATE);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileOutputStream, "UTF-8");

            serializer.startDocument("UTF-8", true);
            serializer.startTag(null, "UserData");

            // 保存最高正确次数
            serializer.startTag(null, "highestCorrectCount");
            serializer.text(String.valueOf(highestCorrectCount));
            serializer.endTag(null, "highestCorrectCount");


            serializer.endTag(null, "UserData");
            serializer.endDocument();
            fileOutputStream.close();

            // 如果是新记录，则播放音效
            if (isNewRecord) {
                playNewRecordSound();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 更新正确次数和错误次数的显示
    private void updateCorrectAndErrorCountDisplay() {
        errorCountTextView.setText("错误次数: " + errorCount + " / " + maxErrorsAllowed);
        correctCountTextView.setText("累计正确次数: " + correctCount);

        // 更新上次正确次数和历史最高正确次数
        highestCorrectCountTextView.setText("历史最高正确次数: " + highestCorrectCount);

        updateScoreDisplay();
    }

    private void playNewRecordSound() {
        // 创建 MediaPlayer 对象，播放音频文件
        MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.new_record);
        if (mediaPlayer != null) {
            mediaPlayer.start();
            // 当播放完毕时释放资源
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.release();
                }
            });
        }
    }



    // 从文件中加载用户积分
    private void loadUserScore() {
        try {
            InputStream inputStream = openFileInput("userdata.xml");
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(inputStream, "UTF-8");

            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                String tagName = parser.getName();
                if (eventType == XmlPullParser.START_TAG && "Score".equals(tagName)) {
                    userScore = Integer.parseInt(parser.nextText());
                }
                eventType = parser.next();
            }
            inputStream.close();
            updateScoreDisplay();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 保存用户积分到文件中
    private void saveUserScore() {
        try {
            FileOutputStream fileOutputStream = openFileOutput("userdata.xml", MODE_PRIVATE);
            XmlSerializer serializer = Xml.newSerializer();
            serializer.setOutput(fileOutputStream, "UTF-8");

            serializer.startDocument("UTF-8", true);
            serializer.startTag(null, "UserData");
            serializer.startTag(null, "Score");
            serializer.text(String.valueOf(userScore));
            serializer.endTag(null, "Score");
            serializer.endTag(null, "UserData");
            serializer.endDocument();
            fileOutputStream.close();
            updateScoreDisplay();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 更新积分显示
    private void updateScoreDisplay() {
        scoreTextView.setText("当前积分: " + userScore);
    }

    private Bitmap loadImageFromAssets(String fileName) {
        try {
            InputStream is = getAssets().open(fileName);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(is, null, options);
            is.close();
            options.inSampleSize = calculateInSampleSize(options, imageGrid.getWidth() / 3, imageGrid.getWidth() / 3);
            is = getAssets().open(fileName);
            options.inJustDecodeBounds = false;
            Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
            is.close();
            return bitmap;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = Math.min(heightRatio, widthRatio);
        }

        return inSampleSize;
    }
}
